import HandleBtn from '@/components/HandleBar/btn';
import type { ProColumns } from '@/components/Pro/';
import { ProTable } from '@/components/Pro/';
import { getFilterList, parseArray } from '@/pages/Statistics/Battery/utils';
import {
  statisticCurrentControllerExportReport,
  statisticCurrentControllerGetSocList,
} from '@/services/ess/statisticBatteryCurrent';
import {
  statisticSocControllerExportReport,
  statisticSocControllerGetSocList,
} from '@/services/ess/statisticBatterySoc';
import {
  statisticVoltageControllerExportReport,
  statisticVoltageControllerGetSocList,
} from '@/services/ess/statisticBatteryVoltage';
import { downloadFetch } from '@/utils/downloadFile';
import { useIntl } from '@umijs/max';
import { message, type DatePickerProps } from 'antd';
import moment from 'moment';
import React, { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { useModel } from 'umi';
import { transformStatisticMultiObjectResponse } from '../../helper';
import './Common.less';

const TableList: React.FC<{
  type: number;
  deviceInfo: API.DeviceInfo[];
}> = ({ type, deviceInfo }, ref) => {
  const intl = useIntl();
  const formRef = useRef(null);
  const { stationId } = useModel('@@initialState')?.initialState || {};
  const [isCollapsed, setIsCollapsed] = useState(true);
  const { initialState } = useModel('@@initialState');
  useImperativeHandle(ref, () => ({
    download: () => {
      const value = formRef?.current?.getFieldsFormatValue() || {};
      if (!value?.codes || !value?.codes?.length) {
        message.warning(intl.formatMessage({ id: 'statistics.analyze.objWarning' }));
        return;
      }
      let downloadFile;
      const ans = parseArray(value.codes, true);
      const filterList = getFilterList(ans);
      if (type === 1) {
        if (ans.nodeType.length) {
          let hasAreaNode: boolean = false;
          hasAreaNode = ans.nodeType.some((item: string) => {
            return item === 'AREA';
          });
          if (hasAreaNode) {
            value.areaList = filterList.areaList;
            value.codes = filterList.codeList;
          } else {
            value.codes = filterList.codeList;
            value.areaList = null;
          }
        }
        downloadFile = statisticSocControllerExportReport;
      } else if (type === 2) {
        value.codes = filterList.codeList;

        downloadFile = statisticVoltageControllerExportReport;
      } else if (type === 3) {
        value.codes = filterList.codeList;

        downloadFile = statisticCurrentControllerExportReport;
      }
      downloadFetch(downloadFile, { stationId: stationId, ...value });
    },
  }));

  const disabledDate: DatePickerProps['disabledDate'] = (current) => {
    const disabled = current && current >= moment().endOf('day');
    return disabled;
  };

  const baseColumns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'batteryVoltage.tableNo' }),
      dataIndex: 'pageIndex',
      hideInSearch: true,
      width: 100,
      fixed: 'left',
    },
    {
      title: intl.formatMessage({ id: 'statistics.income.select' }),
      dataIndex: 'startDate',
      initialValue: moment(),
      valueType: 'date',
      fieldProps: {
        disabledDate: disabledDate,
        allowClear: false,
      },
      hideInTable: true,
    },
    {
      title: intl.formatMessage({ id: 'statistics.curve.selObject' }),
      dataIndex: 'codes',
      valueType: 'treeSelect',
      hideInTable: true,
      initialValue:
        type === 1
          ? deviceInfo[0]?.code && [deviceInfo[0]?.code]
          : initialState?.isArea
          ? deviceInfo[0].children[0]?.code && [deviceInfo[0].children[0]?.code]
          : [deviceInfo[0]?.code],
      fieldProps: {
        treeData: deviceInfo,
        fieldNames: {
          label: 'name',
          value: 'code',
          children: 'children',
        },
        multiple: true,
        maxTagCount: 'responsive',
        showSearch: true,
        treeNodeFilterProp: 'name',
        maxCount: 100,
      },
    },
    {
      title: intl.formatMessage({ id: 'statistics.curve.interval' }),
      dataIndex: 'interval',
      hideInTable: true,
      initialValue: 30,
      valueType: 'select',
      fieldProps: {
        options: [
          {
            label: `30${intl.formatMessage({ id: 'global.secondUnit' })}`,
            value: 30,
          },
          {
            label: `1${intl.formatMessage({ id: 'global.minuteUnit' })}`,
            value: 60,
          },
          {
            label: `2${intl.formatMessage({ id: 'global.minuteUnit' })}`,
            value: 60 * 2,
          },
          {
            label: `5${intl.formatMessage({ id: 'global.minuteUnit' })}`,
            value: 60 * 5,
          },
          {
            label: `10${intl.formatMessage({ id: 'global.minuteUnit' })}`,
            value: 60 * 10,
          },
          {
            label: `30${intl.formatMessage({ id: 'global.minuteUnit' })}`,
            value: 60 * 30,
          },
          {
            label: `1${intl.formatMessage({ id: 'global.hourUnit' })}`,
            value: 60 * 60,
          },
        ],
        allowClear: false,
      },
    },
    {
      title: intl.formatMessage({ id: 'statistics.curve.point' }),
      dataIndex: 'ts',
      hideInSearch: true,
      width: 156,
      fixed: 'left',
    },
    {
      title: intl.formatMessage({ id: 'statistics.curve.object' }),
      dataIndex: 'deviceName',
      hideInSearch: true,
      hideInTable: type !== 1,
    },
    {
      title: 'SOC',
      dataIndex: 'soc',
      hideInSearch: true,
      render: (_, record) => {
        if ((record.soc ?? '') !== '') {
          return record.soc + '%';
        } else {
          return '-';
        }
      },
      hideInTable: type !== 1,
    },
    // {
    //   title: `${intl.formatMessage({ id: 'statistics.curve.VoltageVal' })}(V)`,
    //   dataIndex: 'voltage',
    //   hideInSearch: true,
    //   hideInTable: type !== 2,
    // },
    // {
    //   title: `${intl.formatMessage({ id: 'statistics.curve.currentVal' })}(A)`,
    //   dataIndex: 'current',
    //   hideInSearch: true,
    //   hideInTable: type !== 3,
    // },
  ];

  const [columns, setColumns] = useState(baseColumns);

  const handleSearchToggle = (collapsed: boolean) => {
    setIsCollapsed(collapsed);
  };

  return (
    <div>
      <ProTable<
        API.EditEventReq,
        {
          stationId?: string | number;
          codes?: string[];
          startDate?: string;
          interval?: number;
        }
      >
        headerTitle=" "
        style={{ position: 'relative', zIndex: '10' }}
        formRef={formRef}
        rowKey={(record) => record.ts + '_' + record.id + '_' + record.deviceName}
        request={async (params) => {
          if (!params.codes || !params.codes?.length) {
            message.warning(intl.formatMessage({ id: 'statistics.analyze.objWarning' }));
            return;
          }
          if (params.codes?.length > 100) {
            message.warning(intl.formatMessage({ id: 'statistics.analyze.objWarning100' }));
            return;
          }
          const ans = parseArray(params.codes, true);
          const filterList = getFilterList(ans);
          if (type === 1) {
            if (ans.nodeType.length) {
              let hasAreaNode: boolean = false;
              hasAreaNode = ans.nodeType.some((item: string) => {
                return item === 'AREA';
              });
              if (hasAreaNode) {
                params.areaIdList = filterList.areaList;
                params.codes = filterList.codeList;
              } else {
                params.codes = filterList.codeList;
                params.areaIdList = null;
              }
            }
            return statisticSocControllerGetSocList(params);
          } else {
            const newParams: typeof params = {
              ...params,
              pageSize:
                params.pageSize! * (typeof params.codes === 'string' ? 1 : params.codes.length),
              codes: params.codes,
            };
            if (type === 2) {
              newParams.codes = filterList.codeList;
              // 电压
              const res = await statisticVoltageControllerGetSocList(newParams);
              const newRes = transformStatisticMultiObjectResponse(res, params, ['voltage']);
              const newRecords = newRes.data?.records;
              if (newRecords.length > 0) {
                const newColumns = baseColumns.concat(
                  newRecords[0].devices.map((item, index) => {
                    return {
                      title: `${item.deviceName ?? ''}-电压(V)`,
                      dataIndex: `voltage${index + 1}`,
                      hideInSearch: true,
                      hideInTable: false,
                      width: 156,
                    };
                  }),
                );
                setColumns(newColumns);
              }
              return newRes;
            } else if (type === 3) {
              newParams.codes = filterList.codeList;

              // 电流
              const res = await statisticCurrentControllerGetSocList(newParams);
              const newRes = transformStatisticMultiObjectResponse(res, params, ['current']);
              const newRecords = newRes.data?.records;
              if (newRecords.length > 0) {
                const newColumns = baseColumns.concat(
                  newRecords[0].devices.map((item, index) => {
                    return {
                      title: `${item.deviceName ?? ''}-${intl.formatMessage({
                        id: 'data.current',
                      })}`,
                      dataIndex: `current${index + 1}`,
                      hideInSearch: true,
                      hideInTable: false,
                      width: 156,
                    };
                  }),
                );
                setColumns(newColumns);
              }
              return newRes;
            }
          }
        }}
        params={{
          stationId,
        }}
        columns={columns}
        scroll={{
          x: 'max-content',
        }}
        search={{
          className: `searchPosInline ${isCollapsed ? '' : 'searchCollapse'}`,
          onCollapse: handleSearchToggle,
        }}
        toolbar={{
          className: 'toobalrZindex',
          actions: [
            // eslint-disable-next-line react/button-has-type
          ],
        }}
      />
    </div>
  );
};

export type ToolBarProps = {
  tableRef: React.MutableRefObject<null>;
};
const ToolBarRender: React.FC<ToolBarProps> = ({ tableRef }) => {
  const intl = useIntl();
  return (
    <>
      <HandleBtn handleType="export" key="export" onClick={() => tableRef?.current?.download()}>
        {intl.formatMessage({ id: 'statistics.common.export' })}
      </HandleBtn>
    </>
  );
};

export default forwardRef(TableList);
export { ToolBarRender };
